// ActionScript file
import com.helloniu.fl.NCHandler;
import com.helloniu.fl.SOHandler;
import com.helloniu.fl.util.Tool;
import com.helloniu.fl.widget.HNCoreCompnent;
import com.helloniu.red5.info.UserInfo;

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.xml.XMLNode;

private var ncHandler:NCHandler = null;
private var soHandler:SOHandler = null;
private var _userID:String = null;

public function initConnection(ancHandler:NCHandler, asoHandler:SOHandler, auserID:String):void {
    this.ncHandler = ancHandler;
    this.soHandler = asoHandler;
    this._userID = auserID;
    this.soHandler.addChangeListener(statusChange);

    //
    asoHandler.setProperty("SomeoneJoin", _userID); // notify server
    ncHandler.call("fl_ClientJoin", null, _userID); // notify all client


    var resp:Responder = new Responder(fl_getUserlistResultFunc);
    ncHandler.call("fl_getUserlist", resp);

    var connComps:Array = [localVideoPanel, remoteVideoPanel];

    for(var i:int = 0; i < connComps.length; i++) {
        var connComp:HNCoreCompnent = connComps[i] as HNCoreCompnent;

        if(connComp == null) {
            return;
        }

        connComp.initConnection(ncHandler, soHandler, _userID);
    }
}

private function fl_getUserlistResultFunc(aa1:* = null, aa2:* =null):void {
    userList = new Array();

    for(var i:int = 0; i < aa1.length; i++) {
       var uinfo:UserInfo = new UserInfo();
       var barr:ByteArray = aa1[i] as ByteArray;
       try {
             barr.position = 0;
            //Tool.traceT("==result=1=:"+barr.readUTF());
              uinfo.parseData(barr);
       }
       catch(e:Error) {
           Tool.traceT("==error=:"+e);
       }

       userList.push(uinfo);
    }

    processUserListChange();
}

private function selectItemChanged(e:*):void {
    setPVSName(null);

    var sobj:Object = userListDG.selectedItem;

    if(sobj == null) {
        return;
    }

    if(sobj.avstream == "OK") {
        setPVSName(sobj.name + "avstream");
    }
}

// set play video stream;
private function setPVSName(sname:String):void {
    remoteVideoPanel.setPlayStreamName(sname);
}


private function statusChange(asoHandler:SOHandler, pname:String = null,
    oldValue:* = null, newValue:* = null):void
{
    if(pname == null) {
        return;
    }

    newValue = asoHandler.getProperty(pname);
//Tool.traceT("===sochange:=====" + pname +"|"+ newValue);
    if(pname == "ChatText") {
        processChatChange(newValue);
    }
    else if(pname == "SomeoneJoin") {
        // do nothing
        if(newValue == _userID) {
        }
        else {
            if(userList == null) {
                userList = new Array();
            }

            userList.push(new UserInfo(newValue + ""));
            processUserListChange();
        }
    }
    else if(pname == "SomeoneLeave") {
        processUserLeave(newValue);
    }
}
private var userList:Array = new Array();

private function processUserLeave(val:*):void {
    var leaveUser:String = val as String;
    var idx:int = -1;

    for(var i:int = 0; i < userList.length; i++) {
        var userObj:Object = userList[i];

        if(userObj.userID == leaveUser) {
            idx = i;
            break;
        }
    }

    userList = Tool.arrayRemove(userList, idx);
    processUserListChange();
}

private function processUserListChange():void {
    userListDG.dataProvider = createDP();
}

private function createDP():XMLList {
    var rootList:XMLNode = (new XMLDocument("<users/>")).firstChild;

    for(var i:int = 0; i < userList.length; i++) {
        var userObj:UserInfo = userList[i] as UserInfo;

        var userXML:XMLNode = Tool.creatXMLNode2("user");
        userXML.appendChild(Tool.creatXMLNode("name", userObj.userID));
        userXML.appendChild(Tool.creatXMLNode("video", userObj.binfo.videoUnit.opened + ""));
        userXML.appendChild(Tool.creatXMLNode("email", ""));

        rootList.appendChild(userXML);
    }

    return new XMLList(rootList).user;
}

private function processChatChange(val:*):void {
    chatLog.text = chatLog.text + " \n " + val;
}

private function chatKeyUp(evt:KeyboardEvent):void {
    if(evt.keyCode == Keyboard.ENTER) {
        var str:String = chatTxt.text;
        str = _userID + ":" + str;

        soHandler.setProperty("ChatText", str);
        chatTxt.text = "";
    }
}

public function updateUserInfo(uid:String, key:String, value:*):void {
    for(var i:int = 0; i < userList.length; i++) {
        var userObj:UserInfo = userList[i] as UserInfo;

        if(userObj.userID == uid) {
            if("video" == userObj.binfo.videoUnit.type) {
                userObj.binfo.videoUnit.opened = value;
            }
            break;
        }
    }

    processUserListChange();
}